#!/usr/local/bin/perl
#
# NetList compiler, Perl clone of "nlist.c". Written by Thierry Bousch
# for the BloufGate project and placed in the public domain.
# 
# Usage: nlist [-c] [--city] <nodelist> [netlist]
#
# The flag -c (short form) or --city (long form) appends the name of the
# city to the name of the net.
#
# If no netlist name is provided, data will be written on standard output.
#

$Usage = "Usage: nlist [-c] [--city] <nodelist> [netlist]\n";
$use_cities = 0;

# Parse command line

if ($ARGV[0] eq "-c" || $ARGV[0] eq "--city") {
	shift;
	$use_cities = 1;
}

die $Usage unless @ARGV;
$nodelist = shift;
$netlist  = @ARGV ? shift : "-";	# stdout if no netlist name

# Now try to open the files

open(NODELIST,  $nodelist) || die "Can't open file \"$nodelist\" !\n";
open(NETLIST, ">$netlist") || die "Can't open file \"$netlist\" !\n";

print NETLIST "#\n# Nodelist \"$nodelist\" compiled with nlist.pl\n#\n";

# Scan nodelist

$net = $zone = 0;

while (<NODELIST>) {
	# Remove end-of-line terminators, and ^Z if any
	s/[\n\r\032]//g;
	next if /^;/;		# skip comments
	next if /^$/;		# and empty lines
	next if /^,/;		# and those beginning with a comma

	# Break the line into its fields
	($key,$number,$name,$city) = split(/,/);

	if ($key eq "Zone") {
		# New zone
		$net = $zone = $number;
	}
	elsif ($key eq "Region" || $key eq "Net" || $key eq "Host") {
		# New net
		$net = $number;
	}
	else {
		# Not a new zone or net
		next;
	}
	
	if ($net == 0 || $zone == 0) {
		# This should not happen
		warn "Undefined net or zone -- corrupted nodelist?\n";
		next;
	}

	# Write the net, replacing underscores by spaces

	$_ = "$zone:$net $name";
	$_ .= " ($city)" if $use_cities;
	s/_+/ /g;
	print NETLIST "$_\n";
}
